<template>
  <page-card title="接口管理"
             :subTitle="idNum ? '编辑' : '新增'"
             :need-back="true">
    <div class="class_name">
      <a-form-model :model="form"
                    :rules="rules"
                    ref="ruleForm"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                    layout="horizontal">
        <!-- 接口名称 -->
        <a-form-model-item label="接口名称"
                           prop="name">
          <a-input v-model="form.name"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <!-- 接口类型 -->
        <a-form-model-item label="接口类型"
                           prop="interfaceType">
          <a-select v-model="form.interfaceType">
            <a-select-option value="1">读取</a-select-option>
            <a-select-option value="0">写入</a-select-option>
            <a-select-option value="2">认证</a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 描述 -->
        <a-form-model-item label="描述"
                           prop="detail">
          <a-input v-model="form.detail"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-divider orientation="left">接口请求</a-divider>
        <!-- 接口地址 -->
        <a-form-model-item label="接口地址"
                           prop="interfaceAddr"
                           help="接口完整地址，例如：http://127.0.0.1:8080">
          <a-input v-model="form.interfaceAddr"
                   placeholder="请输入"
                   :addon-before="$route.query.ipAddr"></a-input>
        </a-form-model-item>
        <!-- 请求协议 -->
        <a-form-model-item label="请求协议"
                           prop="requestMethod">
          <a-radio-group v-model="form.requestMethod"
                         @change="requestMethodChange">
            <a-radio value="1">GET</a-radio>
            <a-radio value="2">POST</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <!-- 请求消息对象 -->
        <a-form-model-item v-if="form.requestMethod == '2'"
                           label="请求消息对象"
                           prop="requestObject">
          <a-textarea v-model="form.requestObject"
                      placeholder="http请求消息对象，例：｛username: ''｝"
                      :auto-size="{ minRows: 5, maxRows: 10 }"></a-textarea>
        </a-form-model-item>
        <div style="text-align:center">
          <a-button type="primary"
                    @click="analysisSend">解析请求消息</a-button>
        </div>
        <div style="width: 70%;margin: 10px auto 0 auto">
          <a-tabs v-model="activeTabKey">
            <a-tab-pane key="1">
              <span slot="tab">
                <a-tooltip placement="top"
                           :mouseEnterDelay="0.3">
                  <template slot="title">
                    <span>解析请求的所有参数字段，添加相应字段描述，例：username:用户名</span>
                  </template>
                  <span>参数</span>
                </a-tooltip>
              </span>
            </a-tab-pane>
            <a-tab-pane key="2">
              <span slot="tab">
                <a-tooltip placement="top"
                           :mouseEnterDelay="0.3">
                  <template slot="title">
                    <span>请求的消息头</span>
                  </template>
                  <span>消息头（headers）</span>
                </a-tooltip>
              </span>
            </a-tab-pane>
            <a-tab-pane key="3"
                        v-if="form.requestMethod != '2'">
              <span slot="tab">
                <a-tooltip placement="top"
                           :mouseEnterDelay="0.3">
                  <template slot="title">
                    <span>GET请求解析的url路径参数</span>
                  </template>
                  <span>path参数</span>
                </a-tooltip>
              </span>
            </a-tab-pane>
          </a-tabs>
          <a-table :columns="obsnedjColumns"
                   :data-source="obsnedjList"
                   :pagination="false"
                   rowKey="jsonKey"
                   :key="timeKey"
                   bordered>

            <template slot="parameterKeyTitle">
              <a-tooltip placement="top"
                         :mouseEnterDelay="0.3">
                <template slot="title">
                  <span>消息头元素，例如：Content-Type</span>
                </template>
                <span>类型</span>
              </a-tooltip>
            </template>

            <template slot="parameterValueTitle">
              <a-tooltip placement="top"
                         :mouseEnterDelay="0.3">
                <template slot="title">
                  <span>消息头元素内容，例如：application/json</span>
                </template>
                <span>内容</span>
              </a-tooltip>
            </template>

            <template slot="parameterValue"
                      slot-scope="text, record">
              <a-input v-model="record.parameterValue"></a-input>
            </template>

            <template slot="parameterKey"
                      slot-scope="text, record">
              <a-input v-model="record.parameterKey"></a-input>
            </template>

            <template slot="acaiton"
                      slot-scope="text, record">
              <a @click="delLine(record)">删除</a>
            </template>
          </a-table>
          <a-button style="margin-top: 10px"
                    v-if="activeTabKey == '2'"
                    @click="addLine">添加 +</a-button>

        </div>

        <!-- 接口响应对象 -->
        <a-divider orientation="left">接口响应</a-divider>
        <a-form-model-item label="响应消息对象"
                           prop="responseObject">
          <a-textarea v-model="form.responseObject"
                      placeholder="http响应消息对象，例：{code: 0, message: '操作成功！', data: [{username: ''}]}"
                      :auto-size="{ minRows: 5, maxRows: 10 }"></a-textarea>
        </a-form-model-item>
        <div style="text-align:center">
          <a-button type="primary"
                    @click="analysis(form.responseObject)">解析请求消息</a-button>
        </div>
        <a-table :columns="columns"
                 :data-source="dataList"
                 rowKey="jsonKey"
                 :pagination="false"
                 style="width: 70%; margin: 10px auto 0 auto"
                 bordered>

          <template slot="parameterKeyTitle">
            <a-tooltip placement="top"
                       :mouseEnterDelay="0.3">
              <template slot="title">
                <span>解析相应消息的所有数据字段</span>
              </template>
              <span>字段名称</span>
            </a-tooltip>
          </template>

          <template slot="returnTypeTitle">
            <a-tooltip placement="top"
                       :mouseEnterDelay="0.3">
              <template slot="title">
                <span>需要指定响应消息体字段的类型，分别为消息(message)、数据(data)、状态码(code)、token(token)</span>
              </template>
              <span>数据解析</span>
            </a-tooltip>
          </template>

          <template slot="selfTypeTitle">
            <a-tooltip placement="top"
                       :mouseEnterDelay="0.3">
              <template slot="title">
                <span>字段类型设置，例：String，Object， Number</span>
              </template>
              <span>字段类型</span>
            </a-tooltip>
          </template>

          <template slot="parameterNameTitle">
            <a-tooltip placement="top"
                       :mouseEnterDelay="0.3">
              <template slot="title">
                <span>对应字段的显示名称</span>
              </template>
              <span>显示名称</span>
            </a-tooltip>
          </template>

          <template slot="parameterValueTitle">
            <a-tooltip placement="top"
                       :mouseEnterDelay="0.3">
              <template slot="title">
                <span>设置接口调用成功标识</span>
              </template>
              <span>成功值</span>
            </a-tooltip>
          </template>

          <template slot="returnType"
                    slot-scope="text, record">
            <a-select v-model="record.returnType"
                      style="width:120px"
                      :key="timeKey"
                      allowClear
                      @change="(e)=>returnTypeChange(e, record)">
              <a-select-option value="1"
                               :disabled="disableMSG">消息</a-select-option>
              <a-select-option value="2"
                               :disabled="disableDATA">数据</a-select-option>
              <a-select-option value="3"
                               :disabled="disableSTAUTS">状态码</a-select-option>
              <a-select-option value="4"
                               :disabled="disableTOKEN">token</a-select-option>
            </a-select>
          </template>
          <template slot="parameterName"
                    slot-scope="text, record"
                    v-if="!record.returnType">
            <a-input v-model="record.parameterName"></a-input>
          </template>
          <template slot="parameterValue"
                    slot-scope="text, record"
                    v-if="record.returnType == 3">
            <a-input v-model="record.parameterValue"></a-input>
          </template>
          <template slot="_selfType"
                    slot-scope="text">
            <a-tag :color="(text.includes('array') || text.includes('object')) ? '#87d068' : '#2db7f5'">{{ text }}</a-tag>
          </template>
        </a-table>

        <div style="text-align:center;margin-top:10px">
          <ZOkButton @click="handleSave"></ZOkButton>
        </div>
      </a-form-model>
    </div>
  </page-card>
</template>

<script>

import { saveOrUpdate, connectorinterfaceInfo, buildData, queryInterfaceAndParamterData } from '../../api/connector-manage'
import { ZOkButton } from '@zh/components-ant'
import { analysisJson, isJSON, parseSearchArgs, treeToList, delNullChild } from './method'
import _isEmpty from 'lodash/isEmpty'
import _cloneDeep from 'lodash/cloneDeep'

const col1 = [
  {
    title: '参数名称',
    dataIndex: 'parameterKey',
    key: 'parameterKey'
  },
  {
    title: '描述',
    dataIndex: 'parameterValue',
    key: 'parameterValue',
    scopedSlots: { customRender: 'parameterValue' }
  }
]

const col2 = [
  {
    dataIndex: 'parameterKey',
    key: 'parameterKey',
    slots: { title: 'parameterKeyTitle' },
    scopedSlots: { customRender: 'parameterKey' }
  },
  {
    dataIndex: 'parameterValue',
    key: 'parameterValue',
    slots: { title: 'parameterValueTitle' },
    scopedSlots: { customRender: 'parameterValue' }
  },
  {
    title: '操作',
    dataIndex: 'acaiton',
    key: 'acaiton',
    scopedSlots: { customRender: 'acaiton' }
  }
]

const col3 = [
  {
    title: 'path变量',
    dataIndex: 'parameterKey',
    key: 'parameterKey'
  },
  {
    title: '描述',
    dataIndex: 'parameterValue',
    key: 'parameterValue',
    scopedSlots: { customRender: 'parameterValue' }
  }
]

const columns = [
  {
    dataIndex: 'parameterKey',
    width: 200,
    slots: { title: 'parameterKeyTitle' },
    key: 'parameterKey'
  },
  {
    dataIndex: 'returnType',
    key: 'returnType',
    width: 120,
    slots: { title: 'returnTypeTitle' },
    scopedSlots: { customRender: 'returnType' }
  },
  {
    dataIndex: 'selfType',
    key: 'selfType',
    width: 100,
    slots: { title: 'selfTypeTitle' },
    scopedSlots: { customRender: '_selfType' }
  },
  {
    dataIndex: 'parameterName',
    key: 'parameterName',
    width: 100,
    slots: { title: 'parameterNameTitle' },
    scopedSlots: { customRender: 'parameterName' }
  },
  {
    dataIndex: 'parameterValue',
    key: 'parameterValue',
    width: 100,
    slots: { title: 'parameterValueTitle' },
    scopedSlots: { customRender: 'parameterValue' }
  }
]

export default {
  name: 'YfConnectorEdit',
  components: { ZOkButton },
  extends: null,
  mixins: [],
  props: {},
  data () {
    return {
      timeKey: +new Date(),
      idNum: false,
      activeTabKey: '1',
      // 接口响应解析数据
      dataList: [],
      // 接口请求解析数据
      obsnedjColumns: [],
      // tab中的3个数据
      tabList1: [],
      tabList2: [{ parameterKey: '', parameterValue: '', jsonKey: +new Date() }],
      tabList3: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      // 表单数据
      form: {
        name: '',
        requestMethod: '1',
        detail: '',
        interfaceAddr: '',
        interfaceType: '',
        requestObject: '',
        responseObject: ''
      },
      rules: {
        name: [{
          required: true, message: '请输入表单名称', trigger: 'blur'
        }],
        interfaceAddr: [{
          required: true, message: '请输入接口地址', trigger: 'change'
        }]
      },
      columns: columns
    }
  },
  computed: {},
  created () {
    this.idNum = this.$route.query.id
    if (this.idNum != '') {
      this.getInfoByID(this.idNum)
    }
  },
  watch: {
    // // post和get切换初始化值
    // 'form.requestMethod': {
    //   deep: true,
    //   immediate: true,
    //   handler: function (n, o) {
    //     if (o) {
    //       // this.obsnedjList = []
    //       // this.activeTabKey = '1'
    //       // this.tabList1 = []
    //       // this.tabList2 = [{ parameterKey: '', parameterValue: '', jsonKey: +new Date() }]
    //       // this.tabList3 = []
    //       // if (n == '1') {
    //       //   this.form.requestObject = ''
    //       // }
    //     }
    //   }
    // },
    activeTabKey: {
      deep: true,
      immediate: true,
      handler: function (n, o) {
        if (n == '1') {
          this.obsnedjColumns = col1
          this.obsnedjList = this.tabList1
        }
        if (n == '2') {
          this.obsnedjColumns = col2
          this.obsnedjList = this.tabList2
        }
        if (n == '3') {
          this.obsnedjColumns = col3
          this.obsnedjList = this.tabList3
        }
      }
    },
    // 消息和状态码和数据只能选择一次
    dataList: {
      deep: true,
      immediate: true,
      handler: function (n, o) {
        if (!_isEmpty(n)) {
          let list = treeToList(_cloneDeep(n))
          let find = list.find(it => it.returnType == '1')
          let find2 = list.find(it => it.returnType == '3')
          let find3 = list.find(it => it.returnType == '2')
          let find4 = list.find(it => it.returnType == '4')
          this.disableMSG = !!find
          this.disableSTAUTS = !!find2
          this.disableDATA = !!find3
          this.disableTOKEN = !!find4
          this.timeKey = +new Date()
        }
      }
    }
  },
  methods: {
    requestMethodChange (n) {
      this.obsnedjList = []
      this.activeTabKey = '1'
      this.tabList1 = []
      this.tabList2 = [{ parameterKey: '', parameterValue: '', jsonKey: +new Date() }]
      this.tabList3 = []
      if (n == '1') {
        this.form.requestObject = ''
      }
    },
    delLine (record) {
      if (!_isEmpty(this.tabList2) && this.tabList2.length > 1) {
        this.tabList2 = this.tabList2.filter(it => it.jsonKey != record.jsonKey)
      } else {
        this.tabList2 = [{ parameterKey: '', parameterValue: '', jsonKey: +new Date() }]
      }
      this.obsnedjList = this.tabList2
      this.timeKey = +new Date()
    },
    addLine () {
      this.tabList2 = [
        ...this.tabList2,
        { parameterKey: '', parameterValue: '', jsonKey: +new Date() }
      ]
      this.obsnedjList = this.tabList2
      this.timeKey = +new Date()
    },
    returnTypeChange (val, record) {
      // 数据或消息 清除 显示名称 成功值
      if (val == '1' || val == '2') {
        record.parameterName = ''
        record.parameterValue = ''
      }
      // 状态码清除显示名称
      if (val == '3') {
        record.parameterName = ''
      }
    },
    tabChange (val) {
    },
    inputChange (record) {
    },
    // 解析json
    analysisSend () {
      const { interfaceAddr, requestMethod, requestObject } = this.form
      if (!interfaceAddr) {
        return
      }
      if (requestMethod == '1') {
        const [url, query] = interfaceAddr.split('?')
        let reg = /{.*?}/g
        let match = url.match(reg) || []
        if (Array.isArray(match) && match.length > 0) {
          match = match.map(val => val.slice(1, val.length - 1))
        }
        let tabList1 = []
        if (query) {
          let responseObject = parseSearchArgs('?' + query)
          if (!_isEmpty(responseObject)) {
            tabList1 = Object.keys(responseObject)
          }
        }
        // 参数列表
        this.tabList1 = tabList1.map((it, index) => {
          return { parameterKey: it, parameterValue: '', jsonKey: +new Date() + index }
        })
        // path列表
        this.tabList3 = match.map((it, index) => {
          return { parameterKey: it, parameterValue: '', jsonKey: +new Date() + index }
        })
        if (this.activeTabKey == '1') {
          this.obsnedjList = this.tabList1
        }
        if (this.activeTabKey == '2') {
          this.obsnedjList = this.tabList2
        }
        if (this.activeTabKey == '3') {
          this.obsnedjList = this.tabList3
        }
      }
      if (requestMethod == '2') {
        if (requestObject) {
          let objs = analysisJson(JSON.parse(requestObject))
          this.tabList1 = objs
          this.obsnedjList = objs
        }
      }
      this.activeTabKey = '1'
      this.timeKey = +new Date()
    },
    analysis (val) {
      if (val && isJSON(val)) {
        let objs = analysisJson(JSON.parse(val))
        this.dataList = objs
      } else {
        this.message.error('请输入合法的JSON字符串')
      }
    },
    // 根据id返回详情
    getInfoByID (id) {
      queryInterfaceAndParamterData(id).then(response => {
        const {
          connectorInterfaceVo,
          responseParamterVo = {},
          requestParamterVo: {
            getParamters = [],
            paramterDataVoRequestList = [],
            headers = [],
            paths = []
          } = {}
        } = response
        // 处理应用信息
        this.form = {
          ...connectorInterfaceVo
        }
        // 接口响应对象列表
        this.dataList = delNullChild(responseParamterVo.paramterDataVoResponseList)
        // 请求消息对象列表
        this.tabList1 = connectorInterfaceVo.requestMethod == '1' ? getParamters : delNullChild(paramterDataVoRequestList)
        this.tabList2 = _isEmpty(headers) ? [{ parameterKey: '', parameterValue: '', jsonKey: +new Date() }] : headers
        this.tabList3 = paths
        this.activeTabKey = '1'
        this.obsnedjList = this.tabList1
      })
    },
    // 保存
    handleSave () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let val = {
            connectorInterfaceVo: {
              ...this.form,
              connectorId: this.$route.query.connectorId,
              state: '1'
            },
            // 请求解析后参数
            requestParamterVo: {
              ...this.form.requestMethod == '1' ? { getParamters: this.tabList1 } : { paramterDataVoRequestList: this.tabList1 },
              headers: this.tabList2,
              paths: this.tabList3
            },
            // 响应解析后参数
            responseParamterVo: {
              paramterDataVoResponseList: this.dataList
            }
          }
          saveOrUpdate(val).then((response) => {
            this.message.success(this.idNum ? '修改成功！' : '新增成功！')
            if (!this.idNum) {
              this.$router.replace({
                path: '/connector/apiedit',
                query: { id: response, connectorId: this.$route.query.connectorId }
              })
            } else {
              this.getInfoByID(this.idNum)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>